$.namespace('Page.Survey.Design');
//判断浏览窗口大小
var browseWidth = $(window).width(),
    browseHeight = $(window).height(),
    isDrag = false,
    appQuObj = null,
    isSort = false,
    curEditObj = null,
    dwDialogObj = null,
    curEditObjOldHtml = null;

Page.Survey.Design = function () {

    return {
        editor: null,
        init: function (rootId, examineId) {
            Page.Survey.Design.bindOpEven();
            Page.Survey.Design.reloadDesign(rootId, examineId);
            //setInterval(Page.Survey.Design.saveDesign, 5000);
        },

        bindOpEven: function () {
            //保存操作
            $("#saveBtn").unbind("click").bind("click", function () {
                Page.Survey.Design.curEditCallback();
                Page.Survey.Design.dwCommonDialogHide();
                Page.Survey.Design.resetQuItemHover(null);
                Page.Survey.Design.saveDesign();
            });
            //刷新操作
            $("#refreshBtn").unbind("click").bind("click", function () {
                Page.Survey.Design.reloadDesign(rootId, examineId);
            });


            //高级编辑器OK事件
            $("#dwDialogUeOk").unbind("click").bind("click", function () {
                var title = $('#dialogEditor_title').summernote('code');
                var description = $('#dialogEditor_description').summernote('code');
                Page.Survey.Design.setCurEditContent(title,description);
                Page.Survey.Design.curEditCallback();
                $('#adDialog').modal('hide');
                curEditObj = null;
                return false;
            });

            //属性设置保存操作
            $("#dwDialogQuOptionSetSave").click(function () {
                var quItemBody = $(dwDialogObj).parents(".surveyQuItemBody");
                var quOptionParent = $(dwDialogObj).parent();
                //设置回显值 isNote checkType
                var quOption_isNote = $("#modelUIDialog input[name='quOption_isNote']");
                var quOption_rule = $("#modelUIDialog select[name='quOption_rule']");
                var quOption_isRequiredFill = $("#modelUIDialog input[name='quOption_isRequiredFill']");


                var quOption_expressions = $("#modelUIDialog input[name='quOption_expressions']");
                var quOption_isScore = $("#modelUIDialog input[name='quOption_isScore']");
                var quOption_value = $("#modelUIDialog input[name='quOption_value']");


                var isNote = quOptionParent.find("input[name='isNote']");
                var checkType = quOptionParent.find("input[name='rule']");
                var isRequiredFill = quOptionParent.find("input[name='isRequiredFill']");
                var expressions = quOptionParent.find("input[name='expressions']");
                var value = quOptionParent.find("input[name='value']");


                //alert(isNote.attr("name"));
                if (quOption_isNote.prop("checked")) {
                    isNote.val("true");
                    //显示填空框
                    quOptionParent.find(".optionInpText").show();
                } else {
                    isNote.val("false");
                    quOptionParent.find(".optionInpText").hide();
                }
                var checkTypeVal = quOption_rule.val();
                if (checkTypeVal == "") {
                    checkTypeVal = "NO";
                }
                checkType.val(checkTypeVal);
                if (quOption_isRequiredFill.prop("checked")) {
                    isRequiredFill.val("true");
                } else {
                    isRequiredFill.val("false");
                }

                expressions.val(quOption_expressions.val());
                value.val(quOption_value.val());

                Page.Survey.Design.dwCommonDialogHide();
                $("#modelUIDialog").modal("hide")
                quItemBody.find("input[name='saveTag']").val(1);
                return false;
            });

            //设置题目属性保存事件
            $("#dwDialogQuSetSave").click(function () {
                if (dwDialogObj != null) {
                    var quItemBody = $(dwDialogObj).parents(".surveyQuItemBody");

                    var setCellCount = $("#dwCommonDialog select[name='setCellCount']").val();
                    var setIsRequired = $("#dwCommonDialog input[name='setIsRequired']:checked");

                    var setScore = $("#dwCommonDialog input[name='quOption_score']").val();//默认分值
                    var setIsScore = $("#dwCommonDialog input[name='quOption_isScore']:checked");

                    quItemBody.find("input[name='isRequired']").val(setIsRequired[0] ? 'true' : 'false');
                    quItemBody.find("input[name='cellCount']").val(setCellCount);

                    quItemBody.find("input[name='score']").val(setScore);
                    quItemBody.find("input[name='isScore']").val(setIsScore[0] ? 'true' : 'false');

                    quItemBody.find("input[name='saveTag']").val(1);
                    Page.Survey.Design.dwCommonDialogHide();
                }
                return false;
            });

            //填空題属性设置
            $("#dwDialogQuFillOptionSave").click(function () {
                var quItemBody = $(dwDialogObj).parents(".surveyQuItemBody");
                //设置回显值 isNote checkType
                var quFill_rule = $("#modelUIDialog select[name='quFill_rule']");
                var qu_inputWidth = $("#modelUIDialog input[name='qu_inputWidth']");
                var qu_inputRow = $("#modelUIDialog input[name='qu_inputRow']");
                var quOption_expressions = $("#modelUIDialog input[name='quOption_expressions']");

                var ruleType = quItemBody.find("input[name='rule']");
                //输入框 input 大小调整
                var inputWidth = quItemBody.find("input[name='inputWidth']");
                var inputRow = quItemBody.find("input[name='inputRow']");
                var expressions = quItemBody.find("input[name='expressions']");

                var rule_Val = quFill_rule.val();
                if (rule_Val == "") {
                    rule_Val = "NO";
                }
                ruleType.val(rule_Val);

                inputWidth.val(qu_inputWidth.val());
                inputRow.val(qu_inputRow.val());
                expressions.val(quOption_expressions.val());
                //alert(qu_inputRow);
                if (qu_inputRow.val() > 1) {
                    quItemBody.find(".quFillblankAnswerTextarea").show();
                    quItemBody.find(".quFillblankAnswerInput").hide();
                    quItemBody.find(".quFillblankAnswerTextarea").attr("rows", qu_inputRow.val());
                    quItemBody.find(".quFillblankAnswerTextarea").width(qu_inputWidth.val());
                } else {
                    quItemBody.find(".quFillblankAnswerTextarea").hide();
                    quItemBody.find(".quFillblankAnswerInput").show();
                    quItemBody.find(".quFillblankAnswerInput").width(qu_inputWidth.val());
                }

                quItemBody.find(".quCoItemUlLi").removeClass("hover");
                quItemBody.find("input[name='saveTag']").val(1);
                $('#modelUIDialog').modal('hide');

                Page.Survey.Design.resetQuItemHover(null);
                Page.Survey.Design.dwCommonDialogHide();
                return false;
            });

            //保存逻辑设置
            $("#dwDialogSaveLogic").click(function(){
                var quItemBody=$(dwDialogObj).parents(".surveyQuItemBody");
                var quLogicInputCase=quItemBody.find(".quLogicInputCase");
                var dwQuLogicTrs=$("#dwQuLogicTable tr");
                var quLogicItemHtml=$("#quLogicItemModel").html();
                $.each(dwQuLogicTrs,function(){
                    var cgQuItemId=$(this).find(".logicQuOptionSel").val();
                    var skQuId=$(this).find(".logicQuSel").val();
                    var logicType=$(this).find(".logicType").val();
                    var quLogicItemClass=$(this).attr("class");
                    //判断已经保存过的，保存过的只做修改
                    if(skQuId!="" && cgQuItemId!=""){
                        var quLogicItem=quLogicInputCase.find("."+quLogicItemClass);
                        if(quLogicItem[0]){
                            //已经有值--检查值是否有发生变化
                            var oldSkQuId=quLogicItem.find("input[name='ckSurveyId']").val();
                            var oldCgQuItemId=quLogicItem.find("input[name='ckItemId']").val();
                            var oldLogicType=quLogicItem.find("input[name='logicType']").val();
                            if(oldSkQuId!=skQuId || cgQuItemId!=oldCgQuItemId || oldLogicType!=logicType){
                                //后来修复的
                                quItemBody.find("input[name='saveTag']").val("1");
                                quLogicItem.find("input[name='skSurveyId']").val(skQuId);
                                quLogicItem.find("input[name='ckItemId']").val(cgQuItemId);
                                quLogicItem.find("input[name='logicType']").val(logicType);
                            }
                        }else{
                            quLogicInputCase.append(quLogicItemHtml);
                            quLogicItem=quLogicInputCase.find(".quLogicItem").last();
                            quLogicItem.addClass(quLogicItemClass);
                            //修改值
                            quItemBody.find("input[name='saveTag']").val("1");
                            quLogicItem.find("input[name='id']").val("");
                            quLogicItem.find("input[name='skSurveyId']").val(skQuId);
                            quLogicItem.find("input[name='ckItemId']").val(cgQuItemId);
                            quLogicItem.find("input[name='logicType']").val(logicType);
                        }
                    }
                });

                Page.Survey.Design.refreshQuLogicInfo(quItemBody);
                Page.Survey.Design.dwCommonDialogHide();
                return false;
            });


            $('#modelUIDialog').on('hidden.bs.modal', function (e) {
                Page.Survey.Design.dwCommonEditHide();
            })

            $('#adDialog').on('hidden.bs.modal', function (e) {
                Page.Survey.Design.dwCommonEditHide();
            })

            Page.Survey.Design.editor = CodeMirror.fromTextArea(document.getElementById("scoreExpressions"), {
                mode: "text/x-java", //实现Java代码高亮
                //lineNumbers: true,	//显示行号
                theme: "seti",	//设置主题
                lineWrapping: true,//代码折叠
                matchBrackets: true	//括号匹配
            });
            Page.Survey.Design.editor.setSize(null, 230);

        },

        initEven: function () {
            //编辑标题
            $("#dwSurveyName").unbind("click").bind("click", function () {
                Page.Survey.Design.editAble($(this));
                return false;
            });
            //编辑子标题
            $("#dwSurveyNoteEdit").unbind("click").bind("click", function () {
                Page.Survey.Design.editAble($(this));
                return false;
            });

            $("#dwComEditContent").unbind("keyup").bind("keyup", function () {
                $(curEditObj).html($("#dwComEditContent").html());
                $(curEditObj).css("display", "inline-block");

                var dwEditWidth = $(curEditObj).width();
                //var dwEditWidth=$("#dwComEditContent").width();
                var quItemBody = $(curEditObj).parents(".surveyQuItemBody");

                var thClass = $(curEditObj).attr("class");
                if (thClass.indexOf("dwSvyNoteEdit") < 0 && thClass.indexOf("dwSvyName") < 0) {
                    var hv = quItemBody.find("input[name='hv']").val();
                    if (hv == 3) {
                        dwEditWidth > 600 ? dwEditWidth = 600 : dwEditWidth;
                    } else {
                        dwEditWidth < 200 ? dwEditWidth = 200 : dwEditWidth > 600 ? dwEditWidth = 600 : dwEditWidth;
                    }
                } else {
                    dwEditWidth = 680;
                }
                $("#dwCommonEditRoot .dwCommonEdit").css("width", dwEditWidth);
                //设置坐标
                if (curEditObj != null) {
                    var editOffset = $(curEditObj).offset();
                    $("#dwCommonEditRoot").show();
                    $("#dwCommonEditRoot").offset({top: editOffset.top, left: editOffset.left});
                }
            });


            //绑定变动
            Page.Survey.Design.bindQuHoverItem();

        },

        resetQuItemHover: function (quItemBody) {
            $(".surveyQuItemBody").removeClass("hover");
            $(".surveyQuItemBody").find("input[name='hoverTag']").val("0");
            if (quItemBody != null) {
                quItemBody.addClass("hover");
                quItemBody.find("input[name='hoverTag']").val("hover");
            }
        },

        dwCommonDialogHide: function () {
            $("#dwCommonDialog").hide();
            $(".menuBtnClick").removeClass("menuBtnClick");
            dwDialogObj = null;
        },

        curEditCallback: function () {
            if (curEditObj != null) {
                var dwEditHtml = $("#dwComEditContent").html();
                Page.Survey.Design.setCurEditContent(dwEditHtml);
            }
            $("#dwSurveyNote").removeClass("click");
        },

        resetQuItem: function () {
            if (isDrag) {
                isDrag = false;
            }
            var surveyQuItems = $("#dwSurveyQuContent .surveyQuItemBody");
            var indexNum = 1;
            $.each(surveyQuItems, function (i) {
                $(this).find(".quInputCase input[name='orderById']").val(i + 1);
                var quType = $(this).find("input[name='attributeType']").val();
                if (quType != "pagetag" && quType != "paragraph") {
                    $(this).find(".quCoTitle .quCoNum").text((indexNum++) + "、");
                }
            });
            //更新分标标记
            var pageTags = $("#dwSurveyQuContent .surveyQuItemBody input[name='attributeType'][value='pagetag']");
            var pageTagSize = pageTags.size() + 1;
            $.each(pageTags, function (i) {
                var quItemBody = $(this).parents(".surveyQuItemBody");
                var pageQuContent = quItemBody.find(".pageQuContent");
                pageQuContent.text("下一页（" + (i + 1) + "/" + pageTagSize + "）");
            });
        },

        setCurEditContent: function (dwEditHtml1,dwEditHtml2) {
            var thClass = $(curEditObj).attr("class");
            var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
            $(curEditObj).html(dwEditHtml1);
            quItemBody.find("input[name='description']").val(dwEditHtml2);
            Page.Survey.Design.setSaveTag();
            Page.Survey.Design.dwCommonEditHide();
        },
        setSaveTag:function(){
            var quItemBody= $(curEditObj).parents(".surveyQuItemBody");
            quItemBody.find("input[name='saveTag']").val(1);

            var thClass=$(curEditObj).attr("class");
            if(thClass.indexOf("dwSvyName")>0){
                //题目标题
                $(curEditObj).parent().find("input[name='svyNoteSaveTag']").val(1);
            }else if(thClass.indexOf("dwSvyNoteEdit")>=0){
                //问卷欢迎语
                $("input[name='svyNoteSaveTag']").val(1);
            }
        },
        dwCommonEditHide: function () {
            $("#dwCommonEditRoot").hide();
            $(".dwComEditMenuUl").hide();
            curEditObj = null;
        },

        //触发显示编辑
        editAble: function (editAbleObj) {
            var quItemBody = $(editAbleObj).parents(".surveyQuItemBody");
            Page.Survey.Design.resetQuItemHover(quItemBody);

            var thClass = $(editAbleObj).attr("class");
            var editOffset = $(editAbleObj).offset();
            $("#dwCommonEditRoot").removeClass();
            if (thClass.indexOf("quCoTitleEdit") > 0) {
                //题目标题
                $("#dwCommonEditRoot").addClass("quEdit");
            } else if (thClass.indexOf("quCoOptionEdit") > 0) {
                //题目选项
                $("#dwCommonEditRoot").addClass("quOptionEdit");
            } else if (thClass.indexOf("dwSvyNoteEdit") >= 0) {
                //问卷欢迎语
                $("#dwCommonEditRoot").addClass("svyNoteEdit");
            } else if (thClass.indexOf("dwSvyName") >= 0) {
                $("#dwCommonEditRoot").addClass("svyName");
            }
            $("#dwCommonEditRoot").show();
            $("#dwCommonEditRoot").offset({top: editOffset.top, left: editOffset.left});
            $("#dwComEditContent").focus();
            $("#dwComEditContent").html($(editAbleObj).html());
            var dwEditWidth = $(editAbleObj).width();

            //dwEditWidth<200?dwEditWidth=200:dwEditWidth;
            if (thClass.indexOf("dwSvyNoteEdit") < 0 && thClass.indexOf("dwSvyName") < 0) {
                var hv = quItemBody.find("input[name='hv']").val();
                if (hv == 3) {
                    var dwEditText = $(editAbleObj).text();
                    if (dwEditText == "") {
                        dwEditWidth = $(editAbleObj).parents("td").width() - 52;
                    }
                    dwEditWidth > 600 ? dwEditWidth = 600 : dwEditWidth;
                } else {
                    dwEditWidth < 200 ? dwEditWidth = 200 : dwEditWidth > 600 ? dwEditWidth = 600 : dwEditWidth;
                }
            } else {
                dwEditWidth = 680;
            }

            $("#dwCommonEditRoot .dwCommonEdit").css("width", dwEditWidth);
            Page.Survey.Design.setSelectText($("#dwComEditContent"));
            curEditObj = $(editAbleObj);
            curEditObjOldHtml = $(editAbleObj).html();
        },

        setSelectText: function (el) {
            try {
                window.getSelection().selectAllChildren(el[0]); //全选
                window.getSelection().collapseToEnd(el[0]); //光标置后
            } catch (err) {
                //在此处理错误
            }
        },

        bindQuHoverItem: function () {

            $(".SeniorEdit").unbind();
            $(".SeniorEdit").click(function () {
                $('#dialogEditor_title').summernote('code', $(curEditObj).html());
                var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
                var description = quItemBody.find("input[name='description']").val();
                $('#dialogEditor_description').summernote('code', description);
                $('#adDialog').modal();
                return false;
            });

            $(".option_Set").unbind();
            $(".option_Set").click(function () {
                Page.Survey.Design.showUIDialog($(curEditObj))
                return false;
            });


            $("#dwSurveyQuContent .surveyQuItemBody").unbind();
            $("#dwSurveyQuContent .surveyQuItemBody").hover(function () {
                //显示
                if (isDrag) {
                    appQuObj = $(this);
                } else {
                    //显示
                    $(this).addClass("hover");
                    $(".pageBorderTop").removeClass("nohover");
                    //如果是填空
                    appQuObj = $(this);
                }
            }, function () {
                $(this).removeClass("showLine");
                var hoverTag = $(this).find("input[name='hoverTag']").val();
                if (hoverTag != "hover") {
                    $(this).removeClass("hover");
                }
                appQuObj = null;

            });

            $("#dwSurveyQuContent .surveyQuItemBody").click(function () {
                Page.Survey.Design.curEditCallback();
                Page.Survey.Design.dwCommonDialogHide();
                $(".surveyQuItemBody").removeClass("hover");
                $(".surveyQuItemBody").find("input[name='hoverTag']").val("0");
                $(this).addClass("hover");
                return false;
            });

            $(".quCoItemUlLi,.mFillblankTableTr").unbind();
            $(".quCoItemUlLi,.mFillblankTableTr").hover(function () {
                if (!isDrag) {
                    $(this).addClass("hover");
                }
            }, function () {
                var thClass = $(this).attr("class");
                if (thClass.indexOf("menuBtnClick") <= 0) {
                    $(this).removeClass("hover");
                }
            });



            //是否追加备注控制操作
            $(".dwQuRadioCheckboxOption input[name='quOption_isNote']").unbind("click").bind("click", function () {
                var optionCk = $(this).prop("checked");
                if (optionCk) {
                    $(".quOptionFillContentLi,.quOptionFillRequiredLi").show();
                } else {
                    $(".quOptionFillContentLi,.quOptionFillRequiredLi").hide();
                }
            });

            //是否为记分项
            $("#dwCommonDialog input[name='quOption_isScore']").unbind("click").bind("click", function () {
                var optionCk = $(this).prop("checked");
                if (optionCk) {
                    $(".quOptionScoreContentLi").show();
                } else {
                    $(".quOptionScoreContentLi").hide();
                }
            });

            //绑定编辑
            $("#dwSurveyQuContent .editAble").unbind();
            $("#dwSurveyQuContent .editAble").click(function () {
                Page.Survey.Design.editAble($(this));
                return false;
            });

            //绑定题目删除事件
            $(".dwQuDelete").unbind();
            $(".dwQuDelete").click(function () {
                var quBody = $(this).parents(".surveyQuItemBody");
                var quId = quBody.find("input[name='id']").val();
                Bolt.confirm("确认要删除此题吗？", function () {
                    if (quId != "") {
                        Bolt.ajax('doajax', {
                            data: {id: quId},
                            url: '/admin/survey/design/del',
                            type: 'GET',
                            loadingMask: true,
                            okCallback: function (json) {
                                quBody.hide("slow", function () {
                                    $(this).parent().remove();
                                    Page.Survey.Design.dwCommonEditHide();
                                    Page.Survey.Design.resetQuItem();
                                })
                            }
                        })
                    } else {
                        quBody.hide("slow", function () {
                            $(this).parent().remove();
                            Page.Survey.Design.dwCommonEditHide();
                            Page.Survey.Design.resetQuItem();
                        })
                    }
                }, null);
                return false;
            });

            $(".questionUp").unbind();
            $(".questionUp").click(function () {
                var nextQuBody = $(this).parents(".li_surveyQuItemBody");
                var prevQuBody = $(nextQuBody).prev();
                if (prevQuBody[0]) {
                    var prevQuBodyHtml = prevQuBody.html();
                    $(nextQuBody).after("<li class='li_surveyQuItemBody'>" + prevQuBodyHtml + "</li>");
                    var newNextObj = $(nextQuBody).next();
                    newNextObj.hide();
                    newNextObj.slideDown("slow");
                    prevQuBody.slideUp("slow", function () {
                        prevQuBody.remove();
                        Page.Survey.Design.resetQuItem();
                        Page.Survey.Design.bindQuHoverItem();
                    });
                    nextQuBody.find("input[name='saveTag']").val("1");
                } else {
                    notify("已经是第一个了！", 1000);
                }
            });

            $(".questionDown").unbind();
            $(".questionDown").click(function () {
                var prevQuBody = $(this).parents(".li_surveyQuItemBody");
                var nextQuBody = $(prevQuBody).next();
                if (nextQuBody[0]) {
                    var nextQuBodyHtml = nextQuBody.html();
                    $(prevQuBody).before("<li class='li_surveyQuItemBody' >" + nextQuBodyHtml + "</li>");
                    var newPrevObj = $(prevQuBody).prev();
                    newPrevObj.hide();
                    newPrevObj.slideDown("slow");
                    nextQuBody.slideUp("slow", function () {
                        nextQuBody.remove();
                        Page.Survey.Design.resetQuItem();
                        Page.Survey.Design.bindQuHoverItem();
                    });

                    prevQuBody.find("input[name='saveTag']").val("1");
                } else {
                    alert("已经是最后一个了！");
                }
            });

            //题目设置
            $(".dwQuSet").unbind();
            $(".dwQuSet").click(function () {
                Page.Survey.Design.showDialog($(this));
                var quItemBody = $(this).parents(".surveyQuItemBody");
                Page.Survey.Design.resetQuItemHover(quItemBody);
                return false;
            });

            //填空题选项设置
            $(".quFillblankItem .dwFbMenuBtn").unbind();
            $(".quFillblankItem .dwFbMenuBtn").click(function () {
                Page.Survey.Design.showUIDialog($(this));
                return false;
            });

            //窗口关闭
            $("#dwCommonDialogClose").unbind();
            $("#dwCommonDialogClose").click(function () {
                Page.Survey.Design.dwCommonDialogHide();
                Page.Survey.Design.resetQuItemHover(null);
            });
            //分页设置
            $(".dwComEditMenuBtn").unbind();
            $(".dwComEditMenuBtn").click(function () {
                //dwComEditMenuBtn
                var dwMenuUl = $(".dwComEditMenuUl:visible");
                //根据当前编辑的对象
                var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
                var quType = quItemBody.find("input[name='attributeType']").val();
                var curEditClass = $(curEditObj).attr("class");
                if (quType == "radio" || quType == "checkbox") {
                    if (curEditClass.indexOf("quCoTitleEdit") < 0) {
                        $(".dwComEditMenuUl .option_Set_Li").show();
                    } else {
                        $(".dwComEditMenuUl .option_Set_Li").hide();
                    }
                } else {
                    $(".dwComEditMenuUl .option_Set_Li").hide();
                }

                if (dwMenuUl[0]) {
                    $(".dwComEditMenuUl").hide();
                } else {
                    $(".dwComEditMenuUl").show();
                }
                return false;
            });

            //逻辑设置
            $(".dwQuLogic").unbind();
            $(".dwQuLogic").click(function () {

                Page.Survey.Design.showDialog($(this));
                var quItemBody=$(this).parents(".surveyQuItemBody");
                $("#dwQuLogicTable").empty();
                Page.Survey.Design.saveDesign(function(){
                    //逻辑数据回显示
                    var quLogicItems=quItemBody.find(".quLogicItem");
                    if(quLogicItems[0]){
                        $.each(quLogicItems,function(){
                            var ckItemId=$(this).find("input[name='ckItemId']").val();
                            var skSurveyId=$(this).find("input[name='skSurveyId']").val();
                            var logicType=$(this).find("input[name='logicType']").val();
                            var thClass=$(this).attr("class");
                            thClass=thClass.replace("quLogicItem", "");
                            thClass=thClass.replace(" ", "");
                            //回显相应的选项
                            Page.Survey.Design.addQuDialogLogicTr(false,function(){
                                //执行成功--设置值
                                var lastTr=$("#dwQuLogicTable").find("tr").last();
                                lastTr.attr("class",thClass);
                                lastTr.find(".logicQuOptionSel").val(ckItemId);
                                lastTr.find(".logicQuSel").val(skSurveyId);
                                lastTr.find(".logicType").val(logicType);
                                lastTr.find(".logicQuOptionSel").change();
                                lastTr.find(".logicQuSel").change();
                            },function(){});
                        });
                    }else{
                        $(".dwQuDialogAddLogic").click();
                    }
                    Page.Survey.Design.resetQuItemHover(quItemBody);
                })

                return false;
            });

            //-------------------添加題元素选项-----------------
            $(".addOption,.addColumnOption,.addRowOption").unbind();
            $(".addOption,.addColumnOption,.addRowOption").click(function () {
                var quItemBody = $(this).parents(".surveyQuItemBody");
                var quType = quItemBody.find("input[name='attributeType']").val();
                if (quType == "radio") {//添加单选选项
                    Page.Survey.Design.editAble(addRadioItem(quItemBody, "新选项"));
                } else if (quType == "checkbox") {
                    Page.Survey.Design.editAble(addCheckboxItem(quItemBody, "新选项"));
                } else if (quType == "multifillblank") {
                    Page.Survey.Design.editAble(addMultiFillblankItem(quItemBody, "新选项"));
                }
                Page.Survey.Design.bindQuHoverItem();
                return false;
            });

            //批量添加事件
            $(".addMoreOption,.addMoreRowOption,.addMoreColumnOption").unbind();
            $(".addMoreOption,.addMoreRowOption,.addMoreColumnOption").click(function () {
                Page.Survey.Design.showDialog($(this));
                var quItemBody = $(this).parents(".surveyQuItemBody");
                Page.Survey.Design.resetQuItemHover(quItemBody);
                return false;
            });

            //－－－－－－－－－－－－－－－排序上移－－－－－－－－－－－－－－－－－－
            $(".dwOptionUp").unbind();
            $(".dwOptionUp").click(function () {
                //curEditObj
                //判断类型区别table跟ul中的排序
                var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
                var quType = quItemBody.find("input[name='type']").val();

                var nextLi = null;
                var prevLi = null;
                var nextLiAfterHtml = "";
                if (quType === "radio" || quType === "checkbox" || quType === "orderqu") {
                    nextLi = $(curEditObj).parents("li.quCoItemUlLi");
                    prevLi = nextLi.prev();
                    var prevLiHtml = prevLi.html();
                    nextLiAfterHtml = "<li class='quCoItemUlLi'>" + prevLiHtml + "</li>";
                }
                if (nextLi != null) {
                    if (prevLi[0]) {
                        $(nextLi).after(nextLiAfterHtml);
                        prevLi.hide();
                        prevLi.remove();
                        var editOffset = nextLi.find("label.editAble").offset();
                        $("#dwCommonEditRoot").show();
                        $("#dwCommonEditRoot").offset({top: editOffset.top, left: editOffset.left});
                        Page.Survey.Design.bindQuHoverItem();
                        $(curEditObj).click();
                        quItemBody.find("input[name='saveTag']").val("1");
                    } else {
                        alert("已经是第一个了！");
                    }
                }

                return false;
            });

            //－－－－－－－－－－－－－－－排序下移－－－－－－－－－－－－－－－－－－
            $(".dwOptionDown").unbind();
            $(".dwOptionDown").click(function () {
                //判断类型区别table跟ul中的排序
                var quItemBody = $(curEditObj).parents(".surveyQuItemBody");
                var quType = quItemBody.find("input[name='type']").val();
                var prevLi = null;
                var nextLi = null;
                var prevLiBeforeHtml = "";
                if (quType === "radio" || quType === "checkbox" || quType === "orderqu") {
                    prevLi = $(curEditObj).parents("li.quCoItemUlLi");
                    nextLi = prevLi.next();
                    var nextLiHtml = nextLi.html();
                    prevLiBeforeHtml = "<li class='quCoItemUlLi'>" + nextLiHtml + "</li>";
                }
                if (nextLi[0]) {
                    $(prevLi).before(prevLiBeforeHtml);
                    nextLi.hide();
                    nextLi.remove();
                    var editOffset = prevLi.find("label.editAble").offset();
                    $("#dwCommonEditRoot").show();
                    $("#dwCommonEditRoot").offset({top: editOffset.top, left: editOffset.left});
                    Page.Survey.Design.bindQuHoverItem();
                    $(curEditObj).click();
                    quItemBody.find("input[name='saveTag']").val("1");
                } else {
                    alert("已经是最后一个了！");
                }
                return false;
            });

            //删除題无素
            $(".dwOptionDel").unbind();
            $(".dwOptionDel").click(function () {
                if (curEditObj != null) {
                    Page.Survey.Design.deleteDwOption()
                }
                return false;
            });

            //逻辑设置时添加逻辑项
            $(".dwQuDialogAddLogic").unbind();
            $(".dwQuDialogAddLogic").click(function () {
                Page.Survey.Design.addQuDialogLogicTr(true, function () {
                }, function () {
                    alert("此题已经设置了任意选项!");
                });
                return false;
            });

            /** 添加单选选项 **/
            function addRadioItem(quItemBody, itemText) {
                if (itemText == '') {
                    itemText = "请填写标题"
                }
                var newEditObj = null;
                //ul li处理
                var quRadioItemHtml = $("#quRadioItem").html();
                var quCoItemUl = quItemBody.find(".quCoItem ul");
                quCoItemUl.append("<li class='quCoItemUlLi'>" + quRadioItemHtml + "</li>");
                newEditObj = quCoItemUl.find("li:last .editAble");
                newEditObj.text(itemText);
                quItemBody.find("input[name='saveTag']").val("1");
                return newEditObj;
            }


            /** 添加多选选项 **/
            function addCheckboxItem(quItemBody, itemText) {
                if (itemText == '') {
                    itemText = "请填写标题"
                }
                var quRadioItemHtml = $("#quCheckboxItem").html();
                var quCoItemUl = quItemBody.find(".quCoItem ul");
                quCoItemUl.append("<li class='quCoItemUlLi'>" + quRadioItemHtml + "</li>");
                var newEditObj = quCoItemUl.find("li:last .editAble");
                newEditObj.text(itemText);
                quItemBody.find("input[name='saveTag']").val("1");
                return newEditObj;
            }

            function addMultiFillblankItem(quItemBody, itemText) {
                //ul li处理
                var quScoreItemHtml = $("#mFillblankTableModel").html();
                var quCoItemTable = quItemBody.find("table.mFillblankTable");
                quCoItemTable.append("<tr class='mFillblankTableTr'>" + quScoreItemHtml + "</tr>");
                quItemBody.find("input[name='saveTag']").val("1");
                var newEditObj = quCoItemTable.find("tr.mFillblankTableTr:last .editAble");
                newEditObj.text(itemText);
                quItemBody.find("input[name='saveTag']").val("1");
                return newEditObj;
            }

        },
        /** 删除选项 **/
        deleteDwOption: function () {
            var quItemBody=$(curEditObj).parents(".surveyQuItemBody");
            var quType=quItemBody.find("input[name='attributeType']").val(), optionParent = null;
            if(quType=="multifillblank"){
                optionParent=$(curEditObj).parents("tr.mFillblankTableTr");
            }else{
                optionParent  = $(curEditObj).parents("li.quCoItemUlLi");
            }

            var optionId = $(optionParent).find("input[name='itemId']").val();

            if (optionId != '') {
                Bolt.ajax('doajax', {
                    data: {id: optionId},
                    url: '/admin/survey/design/delOption',
                    confirmMsg:"确定删除吗",
                    loadingMask: true,
                    okCallback: function (json) {
                        delQuOptionCallBack(optionParent);
                    }
                })
            } else {
                delQuOptionCallBack(optionParent);
            }


            /** 删除题无素回调**/
            function delQuOptionCallBack(optionParent) {

                if (optionParent) {
                    optionParent.remove();
                }
                Page.Survey.Design.dwCommonEditHide();
                Page.Survey.Design.bindQuHoverItem();
            }

        },

        //拖入题目到问卷中
        initDrag: function () {
            $(".dragQuUl li").draggable({
                connectToSortable: "#dwSurveyQuContentAppUl",
                zIndex: 27000,
                cursor: "move", cursorAt: {left: 40, top: 25},
                scroll: true,
                scrollSensitivity: 30,
                scrollSpeed: 30,
                appendTo: "#dw_body_content",
                helper: function (event) {
                    return $(this).find(".dwQuTypeModel").html();
                },
                start: function (event, ui) {
                    isDrag = true;
                    $("#tools_wrap").css({"zIndex": 30});

                    Page.Survey.Design.resetQuItemHover(null);

                    Page.Survey.Design.dwCommonDialogHide();
                    Page.Survey.Design.curEditCallback();
                },
                drag: function (event, ui) {

                    isDrag = true;
                },
                stop: function (event, ui) {

                    if (!isSort) {
                        $("#tools_wrap").animate({zIndex: 200}, 200, function () {
                            //$("#tools_wrap").css({"zIndex":200});
                            Page.Survey.Design.resetQuItem();
                            Page.Survey.Design.bindQuHoverItem();
                        });
                    }

                    if (false) {
                        isDrag = false;
                        //alert(this);
                        //判断加入----根据initLine显示状态来判断是否加入进去
                        if (appQuObj != null) {
                            //$("#defaultAppQuObj").before($(this).find(".quTypeModel").html());
                            $(appQuObj).before($(this).find(".dwQuTypeModel").html());
                            $(appQuObj).prev().hide();
                            $(appQuObj).prev().removeClass("quDragBody");
                            $(appQuObj).prev().show("slow");
                            Page.Survey.Design.resetQuItem();
                            Page.Survey.Design.bindQuHoverItem();
                        }
                    }
                }
            });

        },
        initSort: function () {
            $("#dwSurveyQuContentAppUl").sortable({
                revert: true,
                delay: 800,
                placeholder: "showLine",
                tolerance: "pointer",
                opacity: 0.7,
                //helper : "clone",
                handle: ".dwQuMove",
                scrollSensitivity: 30,
                scrollSpeed: 30,
                start: function (event, ui) {
                    //$("#tools_wrap").fadeTo("slow", 0.6);
                    $("#tools_wrap").css({"zIndex": 30});
                    $(".showLine").height(ui.item.height());
                    Page.Survey.Design.dwCommonDialogHide();
                    Page.Survey.Design.curEditCallback();
                    isSort = true;
                },
                sort: function (event, ui) {
                    isSort = true;
                    $(".ui-sortable-placeholder").css({"background": "red"});
                },
                receive: function (event, ui) {
                    //当一个已连接的sortable对象接收到另一个sortable对象的元素后触发此事件。
                },
                out: function (event, ui) {
                    //当一个元素拖拽移出sortable对象移出并进入另一个sortable对象后触发此事件。
                    isSort = false;
                },
                update: function (event, ui) {
                    if (!isDrag) {
                        //根据排序ID，计算出是前排序，还是后排序
                        //ui.item.find("input[name='saveTag']").val(0);
                        //$(this).find("input[name='saveTag']").val(0);
                        $("#dwSurveyQuContentAppUl input[name='saveTag']").val("1");
                    }
                },
                stop: function (event, ui) {
                    //console.debug("sort isDrag:"+isDrag+",isSort:"+isSort);
                    if (isDrag) {
                        isDrag = false;
                        isSort = false;
                        ui.item.html(ui.item.find(".dwQuTypeModel").html());
                        ui.item.removeClass("ui-draggable");
                        ui.item.find(".quDragBody").removeClass("quDragBody");
                        //新加入题-选定题目标题
                        ui.item.find(".surveyQuItemBody").addClass("hover");
                        ui.item.addClass("li_surveyQuItemBody");
                        var quType = ui.item.find(".surveyQuItemBody input[name='attributeType']").val();
                        if (quType != "pagetag") {
                            Page.Survey.Design.editAble(ui.item.find(".surveyQuItemBody .quCoTitleEdit"));
                        }

                    }

                    var curItemBodyOffset = ui.item.offset();
                    $("html,body").animate({scrollTop: curItemBodyOffset.top - 370}, 500, function () {
                        $("#tools_wrap").css({"zIndex": 200});
                        Page.Survey.Design.resetQuItem();
                        Page.Survey.Design.bindQuHoverItem();
                    });

                }
            });
        },

        initScrollSet: function () {
            $('.page').scroll(function () {
                var scrollTop = $(this).scrollTop();
                var quDesignDialog = $("#tools_wrap");

                var quDesignHeight = 125;
                if (scrollTop >= quDesignHeight) {
                    quDesignDialog.css({top: (scrollTop - 20) + "px"});
                } else {
                    quDesignDialog.css({top: "0px"});
                }
                //修正当前编辑的浮动编辑区位置
                if (curEditObj != null) {
                    var editOffset = $(curEditObj).offset();
                    $("#dwCommonEditRoot").show();
                    $("#dwCommonEditRoot").offset({top: editOffset.top, left: editOffset.left});
                }
                if (dwDialogObj != null) {
                    Page.Survey.Design.setShowDialogOffset(dwDialogObj);
                }
            });
        },


        //添加逻辑选项
        addQuDialogLogicTr: function (autoClass, trueCallback, falseCallback) {
            //当前题的选项
            var quItemBody = $(dwDialogObj).parents(".surveyQuItemBody");
            var quItemInputCases = quItemBody.find(".quItemInputCase");
            var quLogicInputCase = quItemBody.find(".quLogicInputCase");
            var quType = quItemBody.find("input[name='attributeType']").val();

            var logicQuOptionSels = $("#dwQuLogicTable").find(".logicQuOptionSel");
            //判断有无选项任意选项
            var executeTag = true;
            $.each(logicQuOptionSels, function () {
                var selOptionVal = $(this).val();
                if (selOptionVal == "0") {
                    executeTag = false;
                    return false;
                }
            });

            if (executeTag) {
                var appendTrHtml = $("#setQuLogicItemTrModel").html();
                $("#dwQuLogicTable").append("<tr>" + appendTrHtml + "</tr>");
                var lastTr = $("#dwQuLogicTable").find("tr").last();
                if (quType === "fillblank") {
                    lastTr.find(".ifSpanText1").text("如果回答");
                }
                if (autoClass) {
                    var quLogicItemNum = quLogicInputCase.find("input[name='quLogicItemNum']");
                    var newQuLogicItemNum = (parseInt(quLogicItemNum.val()) + 1);
                    quLogicItemNum.val(newQuLogicItemNum);
                    var newQuLogicItemClass = "quLogicItem_" + newQuLogicItemNum;
                    lastTr.attr("class", newQuLogicItemClass);
                }
                var dwQuOptionSel = lastTr.find(".logicQuOptionSel");
                    $.each(quItemInputCases, function () {
                        var optionText = $(this).parent().find("label.quCoOptionEdit").text();
                        var optionId = $(this).find("input[name='itemId']").val();
                        dwQuOptionSel.append("<option value='" + optionId + "'>" + optionText + "</option>");
                    });

                if (logicQuOptionSels.size() == 0) {
                    dwQuOptionSel.append("<option value='0'>任意选项</option>");
                } else {
                    $("#dwQuLogicTable").find(".logicQuOptionSel option[value='0']").remove();
                }
                if (quType === "fillblank") {
                    dwQuOptionSel.val("0");
                }
                var logicQuSel = lastTr.find(".logicQuSel");
                var quItemBodys = $("#dwSurveyQuContent .surveyQuItemBody");
                $.each(quItemBodys, function () {
                    //logicQuSels
                    if ($(this).find(".quCoTitleEdit")[0]) {
                        //var quCoNumText = $(this).find(".quCoNum").text();
                        var quTitleText = $(this).find(".quCoTitleEdit").text();
                        var quId = $(this).find("input[name='id']").val();
                        logicQuSel.append("<option value='" + quId + "'>" + quTitleText + "</option>");
                    }
                });
                logicQuSel.append("<option value='1'>正常结束（计入结果）</option><option value='2'>提前结束（不计入结果）</option>");
                if (autoClass) {
                    logicQuSel.prepend("<option value=''>-请选择题目-</option>");
                    dwQuOptionSel.prepend("<option value=''>-请选择选项-</option>");
                }
                Page.Survey.Design.bindDialogRemoveLogic();
                trueCallback();
            } else {
                falseCallback();
            }

        },

        bindDialogRemoveLogic:function(){
            $(".dialogRemoveLogic").unbind();
            $(".dialogRemoveLogic").click(function(){
                var logicItemTr=$(this).parents("tr");
                var logicItemTrClass=logicItemTr.attr("class");
                //同时移除页面只保存的信息--注意如果已经保存到库中，修改
                var quItemBody=$(dwDialogObj).parents(".surveyQuItemBody");
                var quLogicItem=quItemBody.find("."+logicItemTrClass);
                if(quLogicItem[0]){
                    //有则判断，是否已经加入到数据库
                    var quLogicIdVal=quLogicItem.find("input[name='logicId']").val();
                    if(quLogicIdVal == ""){
                        quLogicItem.remove();
                        logicItemTr.remove();
                        Page.Survey.Design.refreshQuLogicInfo(quItemBody);
                    }else{
                        Bolt.ajax('doajax', {
                            data: {id: quLogicIdVal},
                            url: '/admin/survey/design/delQuLogicId',
                            loadingMask: true,
                            okCallback: function (json) {
                                quLogicItem.remove();
                                logicItemTr.remove();
                                Page.Survey.Design.refreshQuLogicInfo(quItemBody);
                            }
                        })
                    }
                }

                return false;
            });

            // $(".logicQuSel").unbind();
            // $(".logicQuSel").change(function(){
            //     var thVal=$(this).val();
            //     //当题目选项中选项 提前结束，或正常结束，则不作处理
            //     if(thVal!=="1" && thVal!=="2"){
            //         //移除前面选项中存在的当前被选择的选项
            //         $("#dwQuLogicTable").find(".logicQuSel").not(this).find("option[value='"+thVal+"']").remove();
            //     }
            // });
        },

        //刷新每题的逻辑显示数目
         refreshQuLogicInfo:function(quItemBody){
            var quLogicItems=quItemBody.find(".quLogicItem");
            var quLogicItemSize=quLogicItems.size();
            quItemBody.find(".quLogicInfo").text(quLogicItemSize);
        },

        //显示题目属性设置弹出层
        showDialog: function (thDialogObj) {
            var thObjClass = thDialogObj.attr("class");
            Page.Survey.Design.curEditCallback();
            Page.Survey.Design.setShowDialogOffset(thDialogObj);
            var quItemBody = $(thDialogObj).parents(".surveyQuItemBody");
            $("#dwCommonDialog .dwQuDialogCon").hide();
            if (thObjClass.indexOf("addMoreOption") >= 0) {
                $("#dwCommonDialog .dwQuAddMore").show();
            } else if(thObjClass.indexOf("dwQuLogic")>=0){
                $("#dwCommonDialog .dwQuDialogLogic").show();
            } else if (thObjClass.indexOf("dwQuSet") >= 0) {
                $("#dwCommonDialog .dwQuSetCon").show();

                var quOption_isScore = $("#dwCommonDialog input[name='quOption_isScore']");//是否记分项
                var quOption_score = $("#dwCommonDialog input[name='quOption_score']");//默认分值

                var quType = quItemBody.find("input[name='attributeType']").val();
                var isRequired = quItemBody.find("input[name='isRequired']").val();
                var cellCount = quItemBody.find("input[name='cellCount']").val();
                var isScore_val = quItemBody.find("input[name='isScore']").val();
                var score_val = quItemBody.find("input[name='score']").val();

                if(quType == 'paragraph'){
                    $('#dwCommonDialog .optionIsRequired').hide();
                }else{
                    $('#dwCommonDialog .optionIsRequired').show();
                }

                $("#dwCommonDialog input[name='setIsRequired']").prop("checked", false);

                if (isScore_val == "true") {
                    quOption_isScore.prop("checked", true);
                    $(".quOptionScoreContentLi").show();
                } else {
                    quOption_isScore.prop("checked", false);
                    $(".quOptionScoreContentLi").hide();
                }
                quOption_score.val(score_val);

                if (isRequired == 'true') {
                    $("#dwCommonDialog input[name='setIsRequired']").prop("checked", true);
                }

                $("#dwCommonDialog .optionLayout").hide();

                if (quType === "radio" || quType === "checkbox") {
                    $("#dwCommonDialog .optionLayout").show();
                }
                $("#dwCommonDialog select[name='setCellCount']").val(cellCount);
            }
            dwDialogObj = thDialogObj;
        },
        //组件属性设置弹出层
        showUIDialog: function (thDialogObj) {
            var thObjClass = thDialogObj.attr("class");
            $(".dwQuDialogCon").hide();

            var quOption_isReadOnly = $("#modelUIDialog input[name='quOption_isReadOnly']");//是否可编辑
            var quOption_expressions = $("#modelUIDialog input[name='quOption_expressions']");//表达式
            var quOption_value = $("#modelUIDialog input[name='quOption_value']");//默认分值

            var quOptionParent = $(thDialogObj).parent();

            if (thObjClass.indexOf("dwFbMenuBtn") >= 0) {
                $("#modelUIDialog .dwQuFillDataTypeOption").show();

                var quItemBody = $(thDialogObj).parents(".surveyQuItemBody");
                var checkType_val = quItemBody.find("input[name='rule']").val();
                var inputWidth_val = quItemBody.find("input[name='inputWidth']").val();
                var inputRow_val = quItemBody.find("input[name='inputRow']").val();

                var expression_val = quItemBody.find("input[name='expressions']").val();


                if (checkType_val == "") {
                    checkType_val = "NO";
                }
                var quOption_rule = $("#modelUIDialog select[name='quOption_rule']");
                quOption_rule.val(checkType_val);
                var qu_inputWidth = $("#modelUIDialog input[name='qu_inputWidth']");
                var qu_inputRow = $("#modelUIDialog input[name='qu_inputRow']");
                if (inputWidth_val == 0) {
                    inputWidth_val = "300";
                }
                if (inputRow_val == 0) {
                    inputRow_val = "1";
                }
                qu_inputWidth.val(inputWidth_val);
                qu_inputRow.val(inputRow_val);
                quOption_expressions.val(expression_val);

                Page.Survey.Design.resetQuItemHover(quItemBody);
                $(thDialogObj).parents(".quCoItemUlLi").addClass("menuBtnClick");

            } else if (thObjClass.indexOf("quCoOptionEdit") >= 0) {

                $("#modelUIDialog .dwQuRadioCheckboxOption").show();

                var quOption_isNote = $("#modelUIDialog input[name='quOption_isNote']");
                var quOption_rule = $("#modelUIDialog select[name='quOption_rule']");
                var quOption_isRequiredFill = $("#modelUIDialog input[name='quOption_isRequiredFill']");


                var isNote_val = quOptionParent.find("input[name='isNote']").val();
                var rule_val = quOptionParent.find("input[name='rule']").val();
                var isRequiredFill_val = quOptionParent.find("input[name='isRequiredFill']").val();
                var quOptionValue_val = quOptionParent.find("input[name='value']").val();
                var expression_val = quOptionParent.find("input[name='expressions']").val();
                quOption_expressions.val(expression_val);
                if (rule_val == "") {
                    rule_val = "NO";
                }
                quOption_rule.val(rule_val);

                if (isNote_val == "true") {
                    quOption_isNote.prop("checked", true);
                    $(".quOptionFillContentLi,.quOptionFillRequiredLi").show();
                } else {
                    quOption_isNote.prop("checked", false);
                    $(".quOptionFillContentLi,.quOptionFillRequiredLi").hide();
                }

                if (isRequiredFill_val == "true") {
                    quOption_isRequiredFill.prop("checked", true);
                } else {
                    quOption_isRequiredFill.prop("checked", false);
                }

            }
            var isReadOnly_val = quOptionParent.find("input[name='isReadOnly']").val();

            quOption_isReadOnly.prop("checked", isReadOnly_val == 'true' ? true : false);


            quOption_value.val(quOptionValue_val);

            $('#modelUIDialog').modal();
            dwDialogObj = thDialogObj;
        },

        setShowDialogOffset: function (thDialogObj) {
            var thObjClass = thDialogObj.attr("class");
            if (thObjClass.indexOf("dwFbMenuBtn") < 0 && thObjClass.indexOf("quCoOptionEdit") < 0) {
                var thOffset = thDialogObj.offset();
                $("#dwCommonDialog").show(0, function () {
                    var thOffsetTop = thOffset.top;
                    var thOffsetLeft = thOffset.left + 40;
                    var dwCommonRefIcon = $("#dwCommonDialog").find(".dwCommonRefIcon");
                    dwCommonRefIcon.removeClass("right");
                    dwCommonRefIcon.removeClass("left");
                    browseWidth = $(window).width();
                    browseHeight = $(window).height();
                    if ((thOffsetLeft - 100) > browseWidth / 2) {
                        thOffsetLeft = thOffsetLeft - $("#dwCommonDialog").width() - 50;
                        dwCommonRefIcon.addClass("right");
                    } else {
                        dwCommonRefIcon.addClass("left");
                    }
                    $("#dwCommonDialog").offset({top: thOffsetTop, left: thOffsetLeft});
                });
            }
        },

        reloadDesign: function (rootId, examineId) {
            Bolt.ajax('doajax', {
                type: 'GET',
                url: '/admin/survey/design/getSurvey',
                data: {rootId: rootId, examineId: examineId},
                loadingMask: true,
                okCallback: function (doc) {
                    var html = template('dwSurvey_temp', doc);
                    $('#dw_body_content').empty().html(html);
                    Page.Survey.Design.initDrag();
                    Page.Survey.Design.initSort();
                    Page.Survey.Design.initScrollSet();
                    Page.Survey.Design.initEven();
                }
            })
        },

        saveDesign: function (callback) {
            Page.Survey.Design.curEditCallback();
            Page.Survey.Design.resetQuItemHover(null);

            var quItemBody = $("#dwSurveyQuContent .li_surveyQuItemBody");
            var ajaxArr = [];

            var title = $("#dwSurveyName").html();
            var subtitle = $("#dwSurveyNoteEdit").html();
            var rootId = $('#rootId').val();
            var examineId = $('#examineId').val();
            var rootVersion = $('#rootVersion').val();
            var svyNoteSaveTag = $('#svyNoteSaveTag').val();
            var surveyIsScore = $('#survey_isScore').val();
            var surveyScoreValue = $('#survey_scoreValue').val();

            var orderRank = 1;
            var year = $('#year').val();
            //处理rootId节点
            var rootNode = createSurveyData(rootId, title, subtitle, 0, 'title', 0, rootId,
                examineId, null, false, 0, surveyIsScore, surveyScoreValue,"", rootVersion);

            if(rootVersion == '' || svyNoteSaveTag == '1'){
                ajaxArr.push(doPost(rootNode,quItemBody));
            }
            var parentId = null;
            $.each(quItemBody, function (i) {
                var surveyData = {},quItemOptions=null;


                //逻辑选项
                var quLogicItems = $(this).find(".quLogicItem");

                var quTitle = $(this).find(".quCoTitleEdit").html(), surveyItems = [];

                var saveTag = $(this).find("input[name='saveTag']").val();

                var quType = $(this).find("input[name='attributeType']").val();
                var isRequired = $(this).find("input[name='isRequired']").val();
                var cellCount = $(this).find("input[name='cellCount']").val();
                var isScore = $(this).find("input[name='isScore']").val();
                var score = $(this).find("input[name='score']").val();
                var description = $(this).find("input[name='description']").val();
                var quId = $(this).find("input[name='id']").val();
                var version = $(this).find("input[name='version']").val();
                 if(quType != 'multifillblank'){
                     quItemOptions = $(this).find(".quCoItem li.quCoItemUlLi");
                 }else{
                     quItemOptions= $(this).find(".quCoItem table.mFillblankTable tr td.mFillblankTableEditTd");
                 }

                if (quType == 'paragraph') {//处理段落
                    surveyData = createSurveyData(quId, quTitle, null, 0, 'paragraph',
                        orderRank, rootId, examineId, rootId, false, 0, isScore, score,description, version);
                    if(quId  != ''){
                        parentId = quId;
                    }else{
                        parentId = rootId;
                    }
                } else if (quType == 'pagetag') {//处理分页
                    surveyData = createSurveyData(quId, "分页标记", null, 0, 'pagetag', orderRank, rootId,
                        examineId, rootId, false, 0, isScore, score,"", version);
                } else if (quType == 'checkbox' || quType == 'radio' || quType == 'fillblank' || quType == 'multifillblank') {
                    var fieldOrder = 1;
                    surveyData = createSurveyData(quId, quTitle, "", 1, quType, orderRank, rootId, examineId, parentId,
                        isRequired, cellCount, isScore, score, description,version);
                    $.each(quItemOptions, function (k) {
                        var label = $(this).find("label.quCoOptionEdit").html();
                        var id = $(this).find(".quItemInputCase input[name='itemId']").val();
                        var type = $(this).find(".quItemInputCase input[name='type']").val();
                        var surveyId = $(this).find(".quItemInputCase input[name='surveyId']").val();
                        var rule = $(this).find(".quItemInputCase input[name='rule']").val();
                        var readOnly = $(this).find(".quItemInputCase input[name='isReadOnly']").val();
                        var isNote = $(this).find(".quItemInputCase input[name='isNote']").val();
                        var isRequiredFill = $(this).find(".quItemInputCase input[name='isRequiredFill']").val();
                        var inputWidth = $(this).find(".quItemInputCase input[name='inputWidth']").val();
                        var inputRow = $(this).find(".quItemInputCase input[name='inputRow']").val();
                        var expressions = $(this).find(".quItemInputCase input[name='expressions']").val();
                        var value = $(this).find(".quItemInputCase input[name='value']").val();
                        var version = $(this).find(".quItemInputCase input[name='version']").val();
                        surveyItems.push(createSurveyItem(id, type, label, surveyId, fieldOrder, readOnly,
                            rule, isNote, isRequiredFill, inputWidth, inputRow, expressions, value, version));

                        $(this).addClass("quOption_"+k);
                        fieldOrder++
                    });
                    surveyData['controlList'] = surveyItems;

                    var logicItems = [];
                    $.each(quLogicItems,function(i){
                        var logics = {}
                        logics["logicId"]=$(this).find("input[name='logicId']").val();
                        logics["ckSurveyId"]=quId;
                        logics["examineId"]=examineId;
                        logics["ckItemId"]=$(this).find("input[name='ckItemId']").val();
                        logics["skSurveyId"]=$(this).find("input[name='skSurveyId']").val();
                        logics["logicType"]=$(this).find("input[name='logicType']").val();
                        logics["version"]=$(this).find("input[name='version']").val();
                        logicItems.push(logics)
                    });
                    if(logicItems.length > 0){
                        surveyData['logicList'] = logicItems;
                    }
                }
                if(saveTag == '1'){
                    ajaxArr.push(doPost(surveyData,$(this)));
                }
                orderRank++;
            });
            if(ajaxArr.length > 0){
                $.when(ajaxArr).then(function(e){
                    if(callback != undefined)callback();
                    Bolt.notify("success", "保存成功");
                });
            }else{
                if(callback != undefined)callback();
            }

            function doPost(surveyData,quItemBody) {
               console.log(surveyData)
               return  Bolt.ajax('doajax', {
                    data: JSON.stringify(surveyData),
                    dataType: "json",
                    contentType: 'application/json',
                    url: '/admin/survey/design/saveOrUpdate',
                    loadingMask: true,
                   cache:false,
                   okCallback: function (json) {
                        var data = json['survey'];
                        if(json['attributeType'] == 'title'){
                            rootId =  data['id'];
                            $('#rootId').val(rootId);
                            $('#rootVersion').val(data['version']);
                            $('#svyNoteSaveTag').val(0);
                        }else{
                            quItemBody.find("input[name='saveTag']").val(0);
                            quItemBody.find("input[name='id']").val(data['id']);
                            quItemBody.find("input[name='version']").val(data['version']);
                            var quItems=json['controlList'];
                            if(! $.isEmptyObject(quItems)){
                                $.each(quItems,function(i,item){
                                    var quItemOption=quItemBody.find(".quOption_"+i);
                                    quItemOption.find("input[name='itemId']").val(item.id);
                                    quItemOption.find("input[name='surveyId']").val(data['id']);
                                    quItemOption.find("input[name='version']").val(item['version']);
                                });
                            }

                            var quLogics=json['logicList'];
                            $.each(quLogics,function(i,item){
                                var logicItem=quItemBody.find(".quLogicItem_"+i);
                                logicItem.find("input[name='id']").val(item.id);
                                logicItem.find("input[name='version']").val(item['version']);
                            });

                            if(json['attributeType'] == 'paragraph'){
                                parentId = data['id'];
                            }else{
                                parentId = rootId;
                            }
                        }
                    }
                })
            }


            function createSurveyData(id, title, subTitle, inputTag, attributeType, orderRank, rootId,
                                      examineId, parent, isRequired, cellCount, isScore, score,description, version) {
                var surveyData = {}
                surveyData['title'] = title;
                surveyData['subTitle'] = subTitle;
                surveyData['inputTag'] = inputTag;
                surveyData['id'] = id;
                surveyData['attributeType'] = attributeType;
                surveyData['orderRank'] = orderRank;
                surveyData['rootId'] = rootId;
                if (parent != null) {
                    surveyData['parent'] = {"id": parent};
                }
                surveyData['examineId'] = examineId;
                surveyData['version'] = version;
                surveyData['year'] = year;
                surveyData['isRequired'] = isRequired;
                surveyData['cellCount'] = cellCount;
                surveyData['isScore'] = isScore;
                surveyData['scoreValue'] = score;
                surveyData['description'] = description;
                return surveyData
            }

            function createSurveyItem(id, type, label, surveyId, fieldOrder, readOnly, rule, isNote, isRequiredFill, inputWidth, inputRow, expressions, value, version) {
                var surveyItem = {}
                surveyItem['id'] = id;
                surveyItem['type'] = type;
                surveyItem['label'] = label;
                surveyItem['surveyId'] = surveyId;
                surveyItem['fieldOrder'] = fieldOrder;

                surveyItem['readOnly'] = readOnly;
                surveyItem['rule'] = rule;
                surveyItem['isNote'] = isNote;
                surveyItem['isRequiredFill'] = isRequiredFill;
                surveyItem['examineId'] = examineId;

                surveyItem['inputWidth'] = inputWidth;
                surveyItem['inputRow'] = inputRow;
                surveyItem['expressions'] = expressions;

                surveyItem['value'] = value;

                surveyItem['version'] = version;


                return surveyItem;
            }


        }
    }

}()

$(document).ready(function () {
    Page.Survey.Design.init(rootId, examineId);
});


